import request from '@/utils/request'
import axios from 'axios'
const apiClient = axios.create({
    baseURL: '/api'
})

// 在每次请求前动态设置 Token
apiClient.interceptors.request.use(config => {
    const token = localStorage.getItem('token');
    if (token) {
        config.headers['Authorization'] = 'Bearer ' + token;
    }
    return config;
}, error => {
    return Promise.reject(error);
});

export function getViolationStats(isAdmin = false) {

    // 根据用户角色选择不同的API路径
    const url = isAdmin ? '/admin/workspace/businessData' : '/user/workspace/businessData'
    return request({
        url: url,
        method: 'get'
    })
}

export function getTrendData(params, isAdmin = false) {
    // 根据用户角色选择不同的API路径
    const url = isAdmin ? '/admin/workspace/businessData' : '/user/workspace/businessData'

    return request({
        url: url,
        method: 'get',
        params: params
    })
}
// 获取饼图数据

export function getViolationStatistics(params, role) {
  if (role === 1 || role === 2) {
    return request({
      url: '/admin/report/violationStatistics',
      method: 'get',
      params
    })
  } else {
    //用户端我的违法记录
    return request({
      url: '/user/report/violationStatistics',
      method: 'get',
      params
    })
  }
}

// 获取折线图数据
export function getViolationPie(params, role) {
  if (role === 1 || role === 2) {
    return request({
      url: '/admin/report/violationPie',
      method: 'get',
      params
    })
  } else {
    //用户端待处理申诉
    return request({
      url: '/user/report/waitingAppeal',
      method: 'get',
      params
    })
  }
}

// 导出违法类型分布表
export function exportViolationReport() {
  const token = localStorage.getItem('token');
  const baseUrl = import.meta.env.VITE_APP_BASE_API || '';
  
  // 创建一个临时链接元素
  const link = document.createElement('a');
  link.href = `${baseUrl}/api/admin/report/export`;
  link.setAttribute('download', 'violation_report.xlsx');
  
  // 添加token到请求头
  const headers = new Headers();
  headers.append('Authorization', `Bearer ${token}`);
  headers.append('token', token);
  
  // 使用fetch API发送请求
  fetch(link.href, {
    headers: headers,
    method: 'GET'
  })
  .then(response => response.blob())
  .then(blob => {
    const url = window.URL.createObjectURL(blob);
    link.href = url;
    link.click();
    window.URL.revokeObjectURL(url);
  })
  .catch(error => {
    console.error('下载报表失败:', error);
  });
}
